#!/bin/bash

set -ex

#func define
mtsql_pt_sysbench_func_base()
{
  MTSQL_PT_LOG_FILE_NAME=sysbench_${MTSQL_PT_ACTION}_result_${MTSQL_PT_TEST_CASE}_${MTSQL_PT_THREADS}.log
  echo "Time=$(date) oltp work load ${MTSQL_PT_TEST_CASE} of threads=${MTSQL_PT_THREADS} for action:${MTSQL_PT_ACTION} starting! "

  #empty log file
  echo "">${MTSQL_PT_LOG_FILE_NAME}

  nohup /usr/local/bin/sysbench  \
    ${MTSQL_PT_TEST_CASE}  \
    --mysql-host=${MTSQL_PT_MASTER}  \
    --mysql-port=${MTSQL_PT_PORT}  \
    --mysql-user=${MTSQL_PT_SYSBENCH_USER}  \
    --mysql-password=${MTSQL_PT_PASSWORD}  \
    --mysql-db=${MTSQL_PT_DB}  \
    --mysql-storage-engine=${MTSQL_PT_STORAGE_ENGINE}  \
    --tables=${MTSQL_PT_TABLES}  \
    --table_size=${MTSQL_PT_TABLE_SIZE}  \
    --percentile=${MTSQL_PT_PERCENTILE}  \
    --histogram=${MTSQL_PT_HISTOGRAM}  \
    --report-interval=${MTSQL_PT_REPORT_INTERVAL}  \
    --warmup-time=${MTSQL_PT_WARMUP_TIME}  \
    --mysql-ignore-errors=${MTSQL_PT_MYSQL_IGNORE_ERRORS}  \
    --rate=${MTSQL_PT_RATE}  \
    --skip_trx=${MTSQL_PT_SKIP_TRX}  \
    --threads=${MTSQL_PT_THREADS}  \
    --time=${MTSQL_PT_TIME} \
    --db-ps-mode=${MTSQL_PT_DB_PS_MODE} \
    ${MTSQL_PT_ACTION}  \
    2>&1 >${HOME}/${MTSQL_PT_LOG_FILE_NAME}

  echo "Time=$(date) oltp work load ${MTSQL_PT_TEST_CASE} of threads=${MTSQL_PT_THREADS} for action:${MTSQL_PT_ACTION} end! "
}

mtsql_pt_sysbench_func_prepare()
{
  mysql -h${MTSQL_PT_MASTER} -u${MTSQL_PT_SYSBENCH_USER} -p${MTSQL_PT_PASSWORD} \
    -e "drop database if exists ${MTSQL_PT_DB};create database if not exists ${MTSQL_PT_DB};"

  export MTSQL_PT_ACTION=prepare
  export MTSQL_PT_THREADS=${MTSQL_PT_TABLES}
  mtsql_pt_sysbench_func_base
}

mtsql_pt_sysbench_func_run()
{
  #test
  for MTSQL_PT_THREADS in 16384 8192 4096 2048 1024 512 256 128 64 32 16
#  for MTSQL_PT_THREADS in 4096 8192 16384 2048 1024 512 256 128 64 32 16
#  for MTSQL_PT_THREADS in 4096 8192 2048 1024 512 256 128 64 32 16
#  for MTSQL_PT_THREADS in 4096 2048 1024 512 256 128 64 32 16
#  for MTSQL_PT_THREADS in 2048 1024 512 256 128 64 32 16
#  for MTSQL_PT_THREADS in 16384
#  for MTSQL_PT_THREADS in 8192
#  for MTSQL_PT_THREADS in 4096
#  for MTSQL_PT_THREADS in 2048
#  for MTSQL_PT_THREADS in 32 16
  do
    export MTSQL_PT_ACTION=run
    mtsql_pt_sysbench_func_base
    sleep ${MTSQL_PT_TEST_INTERVAL_TIME}
  done
}
